package com.yuandengta.yomall.ware.listener;

import com.rabbitmq.client.Channel;
import com.yuandengta.common.to.mq.OrderTO;
import com.yuandengta.common.to.mq.StockLockedTO;
import com.yuandengta.yomall.ware.constant.RabbitConstant;
import com.yuandengta.yomall.ware.service.WareSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Rabbit 监听器 {@link StockReleaseListener}
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@RabbitListener(queues = RabbitConstant.STOCK_RELEASE_QUEUE)
@Slf4j
@Component
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 自动解锁库存
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTO lockedTO, Message message, Channel channel) {
        log.info("收到解锁库存信息，{}", lockedTO);
        try {
            wareSkuService.unLockStock(lockedTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 订单关闭解锁库存
     *  防止订单服务卡顿，导致订单状态消息一直无法更改，库存消息优先到期，
     *  查询订单状态始终是新建状态，导致卡顿的订单永远不能解锁库存
     * @param orderTO
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handlerOrderCloseRelease(OrderTO orderTO, Message message, Channel channel){
        log.info("订单关闭准备解锁库存，{}", orderTO);
        try {
            wareSkuService.unLockStock(orderTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
